
#include "wall.h"

void renderWallProjection() {
  int i, j;
  float projectedWallHeight;
  int wallStripHeight;
  int wallTopPixel;
  int wallBottomPixel;
  int textureOffsetX;
  int texNum;
  int distanceFromTop;
  int textureOffsetY;
  colour_t texelColour;
  int texture_width;
  int texture_height;

  for(i=0; i < NUM_RAYS; i++) {
    float perpDistance = rays[i].distance * cos(rays[i].rayAngle - player.rotationAngle);

    //How tall?
    projectedWallHeight = (TILE_SIZE / perpDistance * distProjPlane);
    wallStripHeight = (int)projectedWallHeight;
    wallTopPixel = WINDOW_HEIGHT / 2 - wallStripHeight / 2;
    wallTopPixel = wallTopPixel < 0 ? 0 : wallTopPixel;

    wallBottomPixel = WINDOW_HEIGHT / 2 + wallStripHeight / 2;
    wallBottomPixel = wallBottomPixel > WINDOW_HEIGHT ? WINDOW_HEIGHT : wallBottomPixel;

    // TODO: calculate textureOffsetX

    if(rays[i].wasHitVert) {
      // perform offset for the vertical hit
      textureOffsetX = (int)rays[i].wallHitY % TILE_SIZE;
    } else {
      // perform offset for the horiz hit
      textureOffsetX = (int)rays[i].wallHitX % TILE_SIZE;
    }
    texNum = rays[i].wallHitContent;
    texture_width = wallTextures[texNum - 1].width;
    texture_height = wallTextures[texNum - 1].height;
    for(j=0; j<WINDOW_HEIGHT;j++) {
      if(wallTopPixel <= j && j < wallBottomPixel){
        distanceFromTop = (j + wallStripHeight / 2) - (WINDOW_HEIGHT / 2);
        textureOffsetY = distanceFromTop * ((float)texture_height / wallStripHeight);
        texelColour = wallTextures[texNum-1].texture_buffer[(texture_width * textureOffsetY) + textureOffsetX];
        if(rays[i].wasHitVert)
          changeColourIntensity(&texelColour, 0.6);
        drawPixel(i,j, texelColour);
      } else if(j < wallTopPixel) {
        // Sky
        drawPixel(i,j, 0xFFFFFF00);
      } else if(wallBottomPixel <= j) {
        // Floor
        drawPixel(i,j, 0xFFAAAAAA);
      }
    }
  }
}
